package classes{
	import beniAS3Lib.utils.BeniStr;
	
	import classes.vo.ServiceData;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class CreateService{
		
		
		private var _templateStr:String;
		private var _modelLocator:ModelLocator = ModelLocator.item;
		
		
		public function CreateService(){
			initTemplateStr();
			createFiles();
		}
		
		private function initTemplateStr():void{
			var file:File = File.applicationDirectory.resolvePath('template/#Files/ServiceFile.as_');
			var fs:FileStream = new FileStream();
			fs.open(file, FileMode.READ);
			_templateStr = fs.readUTFBytes(fs.bytesAvailable);
			_templateStr = UtilFun.getReplaceStr(_templateStr);
			fs.close();
		}
		private function createFiles():void{
			var ary:Array = _modelLocator.serviceColl.source;
			var item:ServiceData;
			var content:String;
			var className:String;
			var fileName:String;
			var file:File;
			var fs:FileStream;
			var subFolder:String;
			var tempAry:Array;
			var subPackage:String;
			for each (item in ary){

				tempAry = item.name.split('/');
				if (tempAry.length == 1){
					subFolder = '';
					className = tempAry[0];
					subPackage = '';
				}else{
					subFolder = '';
					subPackage = '';
					for (var i:int=0; i<tempAry.length-1; i++){
						subFolder += tempAry[i] + '/';
						subPackage += '.' + tempAry[i];
					}
					className = tempAry[tempAry.length-1];
				}
				fileName = className + '.as';
				content = BeniStr.multiReplaceByStr(_templateStr, '#ClassName#', className);
				content = BeniStr.multiReplaceByStr(content, '#SubPackage#', subPackage);
				file = new File(_modelLocator.serviceFolder + subFolder + fileName);
				fs = new FileStream();
				fs.open(file, FileMode.WRITE);
				fs.writeUTFBytes(content);
				fs.close();
			}
		}
	}
}